#!/bin/bash

if [ -z $1 ]; then
  echo "Err: no specified configuration file."
  exit 1
fi

#Apply configurations
source "$1"

#Check configurations
if [ -z $PROJ_NAME ]; then
  echo "Err: no specified project name."
  exit 1
fi
if [ -z $PROJ_SUB_NAME ]; then
  echo "Err: no specified sub project name."
  exit 1
fi 
if [ -z $PROJ_INCLUDES ]; then
  echo "Err: no specified project source code files path."
  exit 1
fi

#Define local variables
PROJ_INDEX_DIR=./$PROJ_NAME/$PROJ_SUB_NAME
FIND_OPTS_EXCLUDES=

#Print configurations to consol.
echo PROJ_NAME=${PROJ_NAME}
echo PROJ_SUB_NAME=${PROJ_SUB_NAME}
echo PROJ_INDEX_DIR=${PROJ_INDEX_DIR}

#Create index directory.
if [ -d "$PROJ_INDEX_DIR" ]; then
  read -n 1 -p "$PROJ_INDEX_DIR exists, over write? y/n: " ANSWER 
  echo .
  if [ "$ANSWER" == "y" ]; then
    rm -f $PROJ_INDEX_DIR/cscope.*
  else
    echo "Err: please specify new project name or sub project name."
    exit 1
  fi 
else  
  mkdir -p "$PROJ_INDEX_DIR"
fi

#Get exclude paths for find options...
for eitem in $PROJ_EXCLUDES; do
  if [ ! -z "$eitem" ]; then
    if [ -d "$eitem" ]; then
      FIND_OPTS_EXCLUDES+="! -path \"$eitem/*\" "
    fi
  fi 
done

echo Searching all source codes...

#Get include paths for find options...
for iitem in $PROJ_INCLUDES; do
  if [ ! -z "$iitem" ]; then
    if [ -d "$iitem" ]; then
      echo FIND_OPTS_INCLUDES+="-path \"$iitem/*\" -o "
      eval "find \"$iitem/\" $FIND_OPTS_EXCLUDES \( -name \"*.[chxsS]\" -o -name \"*.cpp\" \) >> \"$PROJ_INDEX_DIR/cscope.files\"" 
    fi
  fi 
done

#echo "find \"$iitem/\" $FIND_OPTS_EXCLUDES ( -name \"*.[chxsS]\" -o -name \"*.cpp\") > \"$PROJ_INDEX_DIR/cscope.files\"" 

cd "$PROJ_INDEX_DIR"

cscope -b -q -k -v 
